<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                               |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: xiangminghu@clcw.com.cn                                        |
// +------------------------------------------------------------------------+
//

namespace AuctionBack\Controller;

/**
 * 自收车辆
 *
 * @author Xmh
 */

use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\CarResource\Car;
use AuctionCore\CarResource\SelfReceiveCar;
use AuctionCore\Fours\Fours;
use AuctionCore\Common\AjaxPage;
use AuctionCore\PurchaseOrder\PurchaseOrder;
use Think\Log;
use AuctionCore\Other\Store;
use AuctionCore\CarOwner\Owner;
use AuctionCore\Cashier\Collection;
use AuctionCore\Cashier\Payment;
use AuctionCore\AuctionOrder\Signature;
use AuctionCore\CarResource\CarSource;
use AuctionCore\ChangeOrder\ChangeOrder;
use AuctionBack\Logic\RefundLogic;
use AuctionBack\Logic\CarReportLogic;

class SelfReceiveCarController extends BaseController
{

    private $SelfReceiveCar;

    public function __construct()
    {
        parent::__construct();
        $this->emp_id = $this->user_info['emp_id'];

        $this->SelfReceiveCar = new SelfReceiveCar();
    }

    public function index()
    {
        $branch_id = $this->user_info['branch_id'];
        //分公司列表
        $bc_list = $this->get_branch_company_list();
        $this->assign('bc_list', $bc_list);
        $this->assign('branch_id', $branch_id);
        $this->display();
    }

    /**
     * 自收车辆列表
     */
    public function self_receive_car_list()
    {
        $page = I("get.p/d", 1);
        $limit = 10;
        $status = I('get.status', 0);
        $pay_status = I('get.pay_status/d', 0);
        $location_area = I('get.location_area', 0);
        if (!$location_area) {
            $location_area = $this->user_info['bc_code'];
        } else {
            $location_area = [$location_area];
        }
        $sno = I("get.sno", '');
        $seller_name = I('get.seller_name');
        $seller_phone = I('get.seller_phone');
        $self_type = I('get.self_type');

        $params = [
            'status' => $status,
            'pay_status' => $pay_status,
            'location_area' => $location_area,
            'sno' => $sno,
            'seller_name' => $seller_name,
            'seller_phone' => $seller_phone,
            'self_type' => $self_type
        ];
        $result = $this->SelfReceiveCar->get_self_receive_car_list($page, $limit, $params);
        $total = $result['total'] > 0 ? $result['total'] : 0;
        $list = $result['list'] > 0 ? $result['list'] : [];
        $Page = new AjaxPage($total, $limit, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $page_show = $Page->show();

        $this->assign('p', $page);
        $this->assign('page', $page_show);
        $this->assign('list', $list);
        $this->assign('status', $status);
        $this->display();
    }


    //待检测列表
    public function waiting_check_list()
    {
        $page = I("get.p", 1);
        $size = 10;
        $params = array();
        $params['status'] = 'waiting';
        $params['pay_status'] = I('get.pay_status/d', 0);
        $params['trace_type'] = -1;
        $params['location_area'] = I('get.location_area');
        if (!$params['location_area']) {
            $params['location_area'] = !$this->is_hq ? array_flip($this->bc_city) : array();
        }
        $params['sno'] = I("get.sno", '');

        //$params['tab'] = 1;

        //获取list
        //$ol = new OwnerList();
        $result = $this->SelfReceiveCar->getWaitingCheckList($page, $size, $params);
        $Page = new \AuctionCore\Common\AjaxPage($result['total'], $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $show = $Page->show(); // 分页显示输出
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('list', $result['list']);
        $this->assign("business_status", C("BUSINESS_STATUS"));
        $this->assign('channel_type', C("CHANNEL_TYPE"));
        $this->assign("params", $params);
        $this->display();
    }

    /**
     * 自收车辆处理页面
     */
    public function self_receive_car_deal()
    {
        $src_id = I('get.id/d', 0);
        $status = I('get.status/d', 0);
        if ($status > 0) {
            $this->helpJsonResult(500, "状态不正确");
        }
        if ($src_id < 1) {
            $this->helpJsRedirect("参数不正确");
        }
        $detail = $this->SelfReceiveCar->self_receive_car_detail($src_id);
        if ($detail['status'] > 0) {
            $this->helpJsRedirect("状态不正确");
        }
        $location_area_code = $detail['location_area_code']; //车辆所在地城市编号
        $map = array();
        $map['status'] = array('eq', 0);
        $map['type'] = 3; //交付店
        $map['city'] = ['in', $location_area_code]; //只能显示车辆所在地的门店
        $store = new Store();
        $stores = $store->get_stores($map); //得到门店
        $first_payment_data = Car::getFirstPaymentBySid($detail['sid']);
        //打款帐号
        $fours = new Fours();
        $fours_detail = $fours->get_fours_info(['channel_id' => $detail['channel_id']]);
//        dump($fours_detail);
        $fours_bank_account = $fours->get_bank_account_list_by_fid($fours_detail['fid']);
        $fours_bank_account_total = count($fours_bank_account);
        $this->assign('first_payment_data', $first_payment_data);
        $this->assign('fours_bank_account', $fours_bank_account);
        $this->assign('fours_bank_account_total', $fours_bank_account_total);
        $this->assign('stores', $stores);
        $this->assign('detail', $detail);
        $this->assign('status', $status);
        $this->display();
    }

    /**
     * 自收车辆查看信息
     */
    public function self_receive_car_view()
    {
        $src_id = I('get.id/d', 0);
        $status = I('get.status/d', 0);
        if ($status < 1) {
            $this->helpJsonResult(500, "状态不正确");
        }
        if ($src_id < 1) {
            $this->helpJsRedirect("参数不正确");
        }
        //$detail = $this->SelfReceiveCar->self_receive_car_detail($src_id);

        $selfCarDetail = $this->SelfReceiveCar->get_self_receive_car_detail($src_id);
        if ($selfCarDetail['d_order_id']) { //有订单号,就一定是其他渠道成交
            $detail = $this->SelfReceiveCar->self_receive_car_and_order_detail($src_id);
        } else {
            $detail = $this->SelfReceiveCar->self_receive_car_detail($src_id);
        }

        if ($detail['status'] < 1) {
            $this->helpJsRedirect("状态不正确");
        }

        $car = new Car($detail['car_id']);
        $carDetail = $car->detail();
        $sid = $carDetail['sid'];
        $firstPaymentData = Car::getFirstPaymentBySid($sid);
        $collectionPaymentData = $this->getCollectionPaymentInfo($detail);
        $this->assign('collection_payment_data', $collectionPaymentData); //收付款信息
        $this->assign('first_payment_data', $firstPaymentData); //首付款信息
        $this->assign('detail', $detail);
        $this->assign('status', $status);
        $this->display();
    }

    /**
     * 得到收付款信息
     *
     * @param array $selfCarDetail 自收车辆数据
     * @return array
     */
    public function getCollectionPaymentInfo($selfCarDetail)
    {
        $data = [];
        $dOrderId = $selfCarDetail['d_order_id'];
        $paymentId = $selfCarDetail['payment_id'];
        if ($dOrderId) { //如果是订单，就表示的是其他渠道成交的
            $collectionId = $selfCarDetail['collection_id'];
            $collectionCarId = $selfCarDetail['collection_id_car'];
            if ($collectionId > 0) { //车主赔付
                $collectionObj = new Collection($collectionId);
                $data['collectionData'] = $collectionObj->getInfo();
                /*if($collectionData['status'] != 1){ //如果未付款，设置收款金额为0
                    $collectionData['amount'] = 0;
                }*/
            }

            if ($collectionCarId > 0) { //应收车款
                $collectionObj = new Collection($collectionCarId);
                $data['collectionData'] = $collectionObj->getInfo();
            }


        } else {
            $orderObj = new AuOrder($selfCarDetail['order_id']);
            $condition = [
                'order_id' => $selfCarDetail['order_id'],
            ];
            $orderCollection = $orderObj->getCollectionOrderRelationByCondition($condition);
            /*$collectionIds = [];
            foreach ($orderCollection as $key => $val){
                $collectionIds[] = $val['collection_id'];
            }*/
            $collectionCondition = [
                'id' => ['in', isset($orderCollection['collection_id']) ? $orderCollection['collection_id'] : ''],
                'payment_type' => 1,
            ];

            $collectionInfo = Collection::getCollectionByCondition($collectionCondition);
            $data['collectionData'] = $collectionInfo[0];
            // print_r($data['collectionData']);die();
        }
        if (!empty($paymentId)) {
            $paymentObj = new Payment($paymentId);
            $data['paymentData'] = $paymentObj->getInfo();
            /*if($paymentData['status'] != 1){ //如果未付款，设置收款金额为0
                $paymentData['amount'] = 0;
            }*/
        }
        return $data;
    }

    /**
     * 自收车辆 - 重拍
     */
    public function self_receive_reauction()
    {
        $src_id = I('post.src_id/d', 0);
        $order_id = I('post.order_id/d', 0);
        $car_id = I('post.car_id/d', 0);
        $is_re_check = I('post.is_re_check/d', 0);

        if ($src_id < 1 || $order_id < 1 || $car_id < 1) {
            $this->helpJsonResult(400, "参数错误");
        }
        $src_info = $this->SelfReceiveCar->get_self_receive_car_detail($src_id);
        if (empty($src_info)) {
            $this->helpJsonResult(400, "未查询到自收车辆信息");
        }
        $reserve_price = I('post.reserve_price');
        if ($reserve_price <= 0) {
            $this->helpJsonResult(400, "请输入正确的保留价");
        }
        $remark = I('post.remark');
        $car = new Car($car_id);
        $car_detail = $car->detail();

        M()->startTrans();
        if ($is_re_check) { // 如果是重新检测的话。操作三步：1.车主信息表中，插入一条记录，状态标注为待检测
            // 2.自收车辆状态修改为已重拍
            // 3.车辆状态更新为10，待检测

            $result = $this->addCarOwner($car);

            $result1 = $this->SelfReceiveCar->update_self_receive_car($src_id,
                [
                    'status' => 1, // 处理状态0、未处理 1、重拍 2、退车 3、交易成功 4、其他渠道成交
                    'reserve_price' => $reserve_price,
                    'remark' => $remark,
                    'emp_id' => $this->emp_id,
                    'emp_name' => $this->user_info['real_name'],
                    'report_type' => 1, //报告处理方式 重新检测
                    'dealtime' => date("Y-m-d H:i:s")
                ]
            );
            $result2 = $car->update([
                'car_status' => 10, // 车辆状态( -1 删除,1 待审核,2 审核失败,3 审核驳回,4 待拍卖,5 拍卖中,6 流拍,7 待重拍, 8 交易失败, 9 交易成功 ,10 待检测 ,11 已退车)
                'reserve_price' => $reserve_price,
                'is_re_check' => 1, //是否重新检测
                'modify_time' => date('Y-m-d H:i:s', time())
            ]);

            if (!$result || $result1 === false || $result2 === false) {
                M()->rollback();
                $this->helpJsonResult(500, "操作失败");
            }

            $this->log_record($car_id, $order_id, '违约车辆重新检测，进入检测调度');
        } else {
            $rs1 = $this->SelfReceiveCar->update_self_receive_car($src_id,
                [
                    'status' => 1,
                    'reserve_price' => $reserve_price,
                    'remark' => $remark,
                    'emp_id' => $this->emp_id,
                    'emp_name' => $this->user_info['real_name'],
                    'dealtime' => date("Y-m-d H:i:s")
                ]
            );
            $rs2 = $car->update([
                'car_status' => 7, //待重拍
                're_auction_type' => 4,// 重拍类型 自收
                're_auction_reason' => $remark,
                'reserve_price' => $reserve_price,
            ]);
            if (!$rs1 || !$rs2) {
                M()->rollback();
                $this->helpJsonResult(500, "操作失败");
            }
        }

        $unlockResult = $this->unLockAll($car); //解锁采购单和采购付款单失败
        if (!$unlockResult) {
            M()->rollback();
            $this->helpJsonResult(500, "解锁采购单，及采购付款单失败!");
        }

        // $carInfo = $car ->detail();
        // $CarSource = new CarSource($carInfo['sid']);
        // $csData = [];
        // $csData['status'] = 100;
        // $res_cs = $CarSource->update($csData);

        M()->commit();
        if ($is_re_check) { //如果是重新检测
            $this->log_record($car_id, $order_id, '自收车辆，重拍且重新检测');
        } else {
            $this->log_record($car_id, $order_id, '自收车辆，重拍');
        }
        $this->helpJsonResult(200, '操作成功');
    }

    /**
     * 添加车主信息
     *
     * @param $car 车对象
     * @return int
     */
    public function addCarOwner($car)
    {
        $reserveTime = I('post.reserve_time'); //检测预约时间
        $reserveStoreId = I('post.reserve_store'); // 检测预约门店
        $remark = I('post.remark');
        $store = new Store();
        $storeData = $store->detail(['store_id' => $reserveStoreId]);

        $carDetail = $car->detail();

        $ownerId = $carDetail['owner_id'];
        $carOwnerObj = new Owner($ownerId);
        $carOwner = $carOwnerObj->detail();

        $carOwnerData['business_status'] = 4;
        $carOwnerData['is_assigned'] = 0;
        $carOwnerData['reserve_time'] = transform_date($reserveTime, 2); //预约时间
        $carOwnerData['reserve_store'] = $reserveStoreId; // 预约门店
        $carOwnerData['service_method'] = 3;
        $carOwnerData['reserve_remark'] = $remark; //检测预约备注
        $carOwnerData['uid'] = $carOwner['uid'];
        $carOwnerData['province'] = $storeData['province'];
        $carOwnerData['city'] = $storeData['city'];
        $carOwnerData['area'] = $storeData['area'];
        $carOwnerData['seller_name'] = $carOwner['seller_name'];
        $carOwnerData['phone'] = $carOwner['phone'];
        $carOwnerData['car_model'] = $carOwner['car_model'];
        $carOwnerData['brand_id'] = $carOwner['brand_id'];
        $carOwnerData['series_id'] = $carOwner['series_id'];
        $carOwnerData['model_id'] = $carOwner['model_id'];
        $carOwnerData['mileage'] = $carOwner['mileage'];
        $carOwnerData['isou_id'] = $carOwner['isou_id'];
        $carOwnerData['comefrom'] = $carOwner['comefrom'];
        $carOwnerData['comefrom_url'] = $carOwner['comefrom_url'];
        $carOwnerData['first_reg_date'] = $carDetail['first_reg_date'];
        $carOwnerData['posttime'] = date('Y-m-d H:i:s', time());
        $carOwnerData['location_area'] = $carOwner['location_area'];
        $carOwnerData['old_car_id'] = $carDetail['car_id'];
        $carOwnerData['modify_time'] = date('Y-m-d H:i:s', time());

        return Owner::create($carOwnerData);
    }

    /**
     * 解锁采购单，及付款单
     *
     * @param $carObj 车源对象
     * @return bool
     */
    public function unLockAll($carObj)
    {
        $carData = $carObj->detail();
        $sid = $carData['sid'];

        $purchaseOrderObj = new PurchaseOrder();
        $purchaseOrderData = $purchaseOrderObj->viewBySid($sid);
        $purchaseOrderId = $purchaseOrderData['id']; //采购单编号

        ///采购单解锁
        $po = new PurchaseOrder($purchaseOrderId);
        $res_purchase_order = $po->unLockById();

        //付款单解锁(采购单)
        $carSource = $carData['car_source'];
        if ($carSource == 1) { //如果是4s店车源，那么付款单类型是 1 1 => '采购应付',
            $payType = 1;
        }
        if ($carSource == 2) { //如果是个人车源，那么付款单类型是 2 	2 => '采购应付（首）',
            $payType = 2;
        }
        $payment_id = $po->getPaymentIdByPoid($payType);//根据采购单编号和付款单类型，找到相应的付款单
        $res_payment = true;
        if ($payment_id) {
            $res_payment = Payment::unlock($payment_id);
        }

        if ($res_purchase_order && $res_payment) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 自收车辆 - 退车
     */
    public function self_receive_refund()
    {
        $src_id = I('post.src_id/d', 0);
        $order_id = I('post.order_id/d', 0);
        $car_id = I('post.car_id/d', 0);
        if ($src_id < 1 || $order_id < 1 || $car_id < 1) {
            $this->helpJsonResult(400, "参数错误");
        }
        $src_info = $this->SelfReceiveCar->get_self_receive_car_detail($src_id);
        if (empty($src_info)) {
            $this->helpJsonResult(400, "未查询到自收车辆信息");
        }
        $remark = I('post.refund_remark');
        if (empty($remark)) {
            $this->helpJsonResult(400, "请输入退车原因");
        }
        $compensate = I('post.compensate');
        if ($compensate < 0) {
            $this->helpJsonResult(400, "金额不能为空");
        }
        $back_method = I('post.back_method', 0);
        $account_id = I('post.account_id');
        $bank_name = I('post.bank_name');
        $card_no = I('post.card_no');
        $account_name = I('post.account_name');
        $car = new Car($car_id);
        $car_info = $car->detail();
        $carReport = new CarReportLogic($car_id);
        $branchId = $carReport->getBranchId();


        //开启事务
        M()->startTrans();

        $paymentAmount = I('post.payment_amount');
        $backReason = I('post.back_reason');
        $remarkAmountOfCar = I('post.remark_amount_of_car');
        $remarkPayment = I('post.remark_payment');

        $selfReceiveCarData = [
            'status' => 2,
            'compensate' => $paymentAmount,
            'remark' => $remark,
            'back_method' => $back_method,
            'back_reason' => $backReason,
            'emp_id' => $this->user_info['emp_id'],
            'emp_name' => $this->user_info['real_name'],
            'dealtime' => date("Y-m-d H:i:s")
        ];

        $refundCarData['back_reason'] = $backReason;
        $refundCarData['compensate'] = $paymentAmount;//付款金额
        $refundCarData['payment_amount'] = $paymentAmount;//付款金额
        $refundCarData['remark_amount_of_car'] = $remarkAmountOfCar; //车款备注
        $refundCarData['remark_payment'] = $remarkPayment; //付款备注
        $acountData = [];
        if ($car_info['car_source'] == 1) { //如果是4s店车源，直接使用传过来的账号信息
            $acountData['card_no'] = $card_no;
            $acountData['bank_name'] = $bank_name;
            $acountData['account_name'] = $account_name;

        } elseif ($car_info['car_source'] == 2) //如果是个人车源，就从签约表中，查询相应的账号信息
        {
            $signatureObj = new Signature();
            $signatureData = $signatureObj->getDetailByOrderId($order_id);

            $acountData['card_no'] = $signatureData['payee_account'];
            $acountData['bank_name'] = $signatureData['deposit_bank'];
            $acountData['account_name'] = $signatureData['payee_name'];
        }

        if ($backReason == 1) { //平台失误
            $lastRefundCarData = $this->platformError($car_info['sid'], $paymentAmount, $order_id, $refundCarData, $acountData, $branchId);
        } elseif ($backReason == 2) { //卖方违约
            $lastRefundCarData = $this->ownerBreach($car_info['sid'], $paymentAmount, $order_id, $refundCarData, $branchId);
        } else { //平退
            $lastRefundCarData = $this->normalRefund($car_info['sid'], $order_id, $refundCarData, $branchId);
        }

        $sid = $car_info['sid'];
        $validateChangeInfo = ChangeOrder::getChangeInfoBySid($sid, 'owner')[0]; //根据sid得到，有效的车主变更单.一般只有一条
        if ($validateChangeInfo) {
            $res_void_last_change = ChangeOrder::voidLastChange($validateChangeInfo['mid'], '');
            if (!$res_void_last_change) {
                M()->rollback();
                $this->helpJsonResult(500, "作废赔付车主付款单失败!");
            }
        }
        //$breachRes = $bc->update($lastBreachData, $bc_id);
        $SelfReceiveCarRes = $this->SelfReceiveCar->update_self_receive_car($src_id, $selfReceiveCarData);
        if (!$SelfReceiveCarRes) {
            M()->rollback();
            Log::record("自收车辆退车,更新自收信息失败。car_id: {$car_id}", "ERR", true);
            $this->helpJsonResult(500, "操作失败");
        }

        $lastRefundCarData['order_id'] = $order_id;
        $lastRefundCarData['car_id'] = $car_id;
        $lastRefundCarData['sid'] = $car_info['sid'];
        $lastRefundCarData['refer_id'] = $src_id;
        $lastRefundCarData['create_time'] = date('Y-m-d H:i:s', time());
        $lastRefundCarData['type'] = 2; //1 违约车辆 2 自收车辆
        unset($lastRefundCarData['payment_amount']);

        $result = RefundLogic::add($lastRefundCarData);
        if (!$result) {
            M()->rollback();
            $this->helpJsonResult(422, '添加退车信息失败');
        }

        $carData = [
            'car_status' => 8,
            'fail_type' => 2,
            'modify_time' => date('Y-m-d H:i:s', time()),
        ];
        if ($car_info['pay_status'] < 2) {
            $carData['pay_status'] = -1;
        }
        $carRes = $car->update($carData);
        if (!$carRes) {
            M()->rollback();
            Log::record("自收车辆退车,更新车辆信息失败。car_id: {$car_id}", "ERR", true);
            $this->helpJsonResult(500, "操作失败");
        }
        //更改车源状态
        $CarSource = new CarSource($car_info['sid']);
        $csData = [];
        $csData['status'] = 600;
        $res_cs = $CarSource->update($csData);

        M()->commit();


        /* //4s店退车 $src_info['compensate_type'] == 1 &&
         if ($back_method == 1 && $car_info['car_source'] == 1) {
             $bank_account = json_encode(
                 [
                     'bank_name' => $bank_name,
                     'card_no' => $card_no,
                     'account_name' => $account_name
                 ]
             );
             $SelfReceiveCarData['fid'] = $account_id;
             $SelfReceiveCarData['bank_account'] = $bank_account;
         }*/

        /*$is_pay = array(
            'owner_id' => $car_info['owner_id'],
            'order_id' => $order_id,
            'car_id' => $car_id,
            'emp_id' => $this->emp_id,
            'back_method' => $back_method,
            'pay_status' => $car_info['pay_status'],
            'three_in_one' => $car_info['three_in_one'],
            'car_source' => $car_info['car_source'],
//            'compensate_type' => $src_info['compensate_type'],
            'compensate' => $compensate
        );
        $rs = $this->SelfReceiveCar->is_compensate_Pay($is_pay);
        if (!$rs) {
            M()->rollback();
            $this->helpJsonResult(500, "操作失败");
        }*/

        /* if ($car_info['pay_status'] > 0) {
             $pay_map = array();
             $pay_map['car_id'] = ['eq', $car_id];
             $pay_map['status'] = ['eq', 0];
             $data = array();
             $data['status'] = 2;
             M('pay_log')->where($pay_map)->save($data);
         }*/
        $this->log_record($car_id, $order_id, '自收车辆，退车');
        $this->helpJsonResult(200, 'success');
    }

    /**
     *
     * 平台失误
     *
     * @param $sid 车源编号
     * @param $paymentAmount 赔付金额
     * @param $order_id 拍单编号
     * @param $selfReceiveCarData 违约车辆数据
     * @param $acountData 账号信息
     * @param $branchId 分公司编号
     * @return bool
     */
    public function platformError($sid, $paymentAmount, $order_id, $selfReceiveCarData, $acountData, $branchId)
    {
        $purchaseOrderObj = new PurchaseOrder();
        $purchaseOrderData = $purchaseOrderObj->viewBySid($sid);
        if (empty($purchaseOrderData)) {
            $this->helpJsonResult('500', '采购单数据有误!');
            return false;
        }
        $purchaseOrderId = $purchaseOrderData['id']; //采购单编号
        $result = $purchaseOrderObj->closeById($purchaseOrderId); //关闭采购单
        if (!$result) {
            M()->rollback();
            $this->helpJsonResult('500', '关闭采购单失败');
        }

        $paymentRelation = $purchaseOrderObj->getPaymentAndPurchaseOrderRelation($purchaseOrderId, [1, 2]);
        $paymentId = $paymentRelation['payment_id'];

        $paymentObj = new Payment($paymentId);
        $paymentData = $paymentObj->getInfo();

        if (!$paymentData) { //如果没有付款单（个人车源，三证不合一的没有首付款单）
            $paymentStatus = 0; //设置状态为0
        } else {
            $paymentStatus = $paymentData['status'];
        }
        if ($paymentStatus == 2 || $paymentStatus == 0) { //如果是未付或者锁定状态,就作废原来的付款单。赔付平台违约金
            ///$amountPaid = '0'; //已付金额等于0
            //$amount = $paymentData['amount']; //原来的付款金额
            if ($paymentData) {
                $oldPaemntData['status'] = 3; //作废原来的未付款单
                $result = $paymentObj->update($oldPaemntData);
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '作废首付款单失败');
                    return false;
                }
            }
            $lastAmount = $paymentAmount; //赔付金额 = 这次要赔付金额

            if ($lastAmount > 0) { //当赔付金额大于零时，生成付款单
                $data['pay_type'] = 6;
                $data['pay_way'] = 2;
                $data['amount'] = $lastAmount;
                $data['create_time'] = date('Y-m-d H:i:s', time());
                $data['bank_name'] = $acountData['bank_name'];
                $data['account_name'] = $acountData['account_name'];
                $data['card_no'] = $acountData['card_no'];
                $data['refer'] = 2; //来源于自收车辆
                $data['branch_id'] = $branchId; // 分公司编号

                $pamentId = Payment::add($data); //6,代表赔付车主的钱
                $result = $purchaseOrderObj->addPaymentAndPurchaseOrderRelation($purchaseOrderId, $pamentId, '6');//6 代表 赔付车主
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加付款单和采购单关系失败');
                    return false;
                }
                $selfReceiveCarData['payment_id'] = $pamentId; //付款单号
            }

        } elseif ($paymentStatus == 1) { //如果已付状态
            $amount = $paymentData['amount']; //原来的付款金额
            $lastAmount = $amount - $paymentAmount; //最后的金额 = 原来的付款金额 - 这次赔付金额
            if ($lastAmount > 0) { //生成收款单
                $data = [
                    'payment_type' => '7',
                    'payment_method' => '1',
                    'amount' => $lastAmount,
                    'refer' => 2, //来源于自收车辆
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'branch_id' => $branchId, // 分公司编号
                ];
                $collectionId = Collection::add($data);
                if ($collectionId === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加收款单失败');
                    return false;
                }
                $auOrderObj = new AuOrder($order_id);
                $result = $auOrderObj->addCollectionAndOrderRelation($order_id, $collectionId, '7'); //7 应收车主
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加收款单失败');
                    return false;
                }

                $selfReceiveCarData['collection_id_car'] = $collectionId; //收款单号

            } elseif ($lastAmount < 0) { //生成付款单
                $data['pay_type'] = 6;
                $data['pay_way'] = 2;
                $data['amount'] = ($paymentAmount - $amount);
                $data['create_time'] = date('Y-m-d H:i:s', time());
                $data['bank_name'] = $paymentData['bank_name'];
                $data['account_name'] = $paymentData['account_name'];
                $data['card_no'] = $paymentData['card_no'];
                $data['refer'] = 2; //来源于自收车辆
                $data['branch_id'] = $branchId; // 分公司编号

                $pamentId = Payment::add($data);
                $result = $purchaseOrderObj->addPaymentAndPurchaseOrderRelation($purchaseOrderId, $pamentId, '6');//6 代表 赔付车主
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加付款单，采购单关系失败');
                    return false;
                }
                $selfReceiveCarData['payment_id'] = $pamentId; //付款单号
            }
        } elseif ($paymentStatus == 3) {
            M()->rollback();
            $this->helpJsonResult(500, "付款单信息有误");
            return false;
        }
        //print_r($breachData);return;
        return $selfReceiveCarData;
    }

    /**
     * 卖方违约
     *
     * @param $sid 车源编号
     * @param $paymentAmount 赔付金额
     * @param $order_id 拍单编号
     * @param $selfReceiveCarData 自收车辆数据
     * @param $branchId 分公司编号
     * @return bool
     */
    public function ownerBreach($sid, $paymentAmount, $order_id, $selfReceiveCarData, $branchId)
    {
        //TODO 根据sid，获取采购单
        $purchaseOrderObj = new PurchaseOrder();
        $purchaseOrderData = $purchaseOrderObj->viewBySid($sid);
        if (empty($purchaseOrderData)) {
            M()->rollback();
            $this->helpJsonResult('500', '采购单数据有误!');
            return false;
        }
        $purchaseOrderId = $purchaseOrderData['id']; //采购单编号
        $result = $purchaseOrderObj->closeById($purchaseOrderId); //关闭采购单
        if ($result === false) {
            M()->rollback();
            $this->helpJsonResult('500', '关闭采购单失败');
            return false;
        }

        //TODO 根据采购单编号和付款单类型，获取相应的付款单
        $paymentRelation = $purchaseOrderObj->getPaymentAndPurchaseOrderRelation($purchaseOrderId, [1, 2]);
        $paymentId = $paymentRelation['payment_id'];

        $paymentObj = new Payment($paymentId);
        $paymentData = $paymentObj->getInfo();
        if (!$paymentData) { //如果没有付款单（个人车源，三证不合一的没有首付款单）
            $paymentStatus = 0; //设置状态为0
        } else {
            $paymentStatus = $paymentData['status'];
        }
        if ($paymentStatus == 2 || $paymentStatus == 0) { //如果是未付或者锁定状态,就直接生成收款单,并作废原来的首付款单
            if ($paymentData) {
                $oldPaemntData['status'] = 3; //作废原来的未付款单
                $result = $paymentObj->update($oldPaemntData);
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '作废首付款单失败');
                    return false;
                }
            }

            if ($paymentAmount > 0) { //生成收款单
                $data = [
                    'payment_type' => '8', //8 车主违约金扣除
                    'payment_method' => '1',
                    'amount' => $paymentAmount,
                    'refer' => 2, //来源于自收车辆
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'branch_id' => $branchId, // 分公司编号
                ];
                $result = $collectionId = Collection::add($data);
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加收款单失败');
                    return false;
                }

                $auOrderObj = new AuOrder($order_id);
                $result = $auOrderObj->addCollectionAndOrderRelation($order_id, $collectionId, '7'); //7 因收车主
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加收款单，拍单关系失败');
                    return false;
                }
                $selfReceiveCarData['collection_id'] = $collectionId; //收款单号
            }
        } elseif ($paymentStatus == 1) { //如果已付状态，就要收回首付款及赔付金额。此时生成两笔收款单一笔收回首付款，一笔收回卖方的赔付
            $amount = $paymentData['amount']; //原来的付款金额

            if ($amount > 0) { //生成 车款（首付款） 收款单
                $data = [
                    'payment_type' => '7', // 应收车主
                    'payment_method' => '1',
                    'amount' => $amount,
                    'refer' => 2, //来源于自收车辆
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'branch_id' => $branchId, // 分公司编号
                ];
                $result = $collectionId = Collection::add($data);
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加收款单失败');
                    return false;
                }
                $auOrderObj = new AuOrder($order_id);
                $result = $auOrderObj->addCollectionAndOrderRelation($order_id, $collectionId, '7'); //7 因收车主
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加收款单，拍单关系失败');
                    return false;
                }
                $selfReceiveCarData['collection_id_car'] = $collectionId; //车款收款单号
            }

            if ($paymentAmount > 0) { //生成 赔付 收款单
                $data = [
                    'payment_type' => '8', //8 车主违约金扣除
                    'payment_method' => '1',
                    'amount' => $paymentAmount,
                    'refer' => 2, //来源于自收车辆
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'branch_id' => $branchId, // 分公司编号
                ];
                $result = $collectionId = Collection::add($data);
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加收款单失败');
                    return false;
                }
                $auOrderObj = new AuOrder($order_id);
                $result = $auOrderObj->addCollectionAndOrderRelation($order_id, $collectionId, '8'); //7 因收车主
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '添加收款单，拍单关系失败');
                    return false;
                }
                $selfReceiveCarData['collection_id'] = $collectionId; //收款单号
            }
        } elseif ($paymentStatus == 3) {
            M()->rollback();
            $this->helpJsonResult(500, "付款单信息有误");
            return false;
        }
        return $selfReceiveCarData;
    }

    /**
     * 正常退款（平退）
     *
     * @param $sid 车源编号
     * @param $order_id 拍单号
     * @param $selfReceiveCarData 自收车辆数据
     * @param $branchId 分公司编号
     * @return bool
     */
    public function normalRefund($sid, $order_id, $selfReceiveCarData, $branchId)
    {
        //TODO 根据sid，获取采购单
        $purchaseOrderObj = new PurchaseOrder();
        $purchaseOrderData = $purchaseOrderObj->viewBySid($sid);
        if (empty($purchaseOrderData)) {
            M()->rollback();
            $this->helpJsonResult('500', '采购单数据有误!');
            return false;
        }
        $purchaseOrderId = $purchaseOrderData['id']; //采购单编号
        $result = $purchaseOrderObj->closeById($purchaseOrderId); //关闭采购单
        if ($result === false) {
            M()->rollback();
            $this->helpJsonResult(500, "关闭采购单失败");
            return false;
        }
        //TODO 根据采购单编号和付款单类型，获取相应的付款单
        $paymentRelation = $purchaseOrderObj->getPaymentAndPurchaseOrderRelation($purchaseOrderId, [1, 2]);
        $paymentId = $paymentRelation['payment_id'];

        $paymentObj = new Payment($paymentId);
        $paymentData = $paymentObj->getInfo();
        if (!$paymentData) { //如果没有付款单（个人车源，三证不合一的没有首付款单）
            $paymentStatus = 0; //设置状态为0
        } else {
            $paymentStatus = $paymentData['status'];
        }

        if ($paymentStatus == 1) { //如果已付状态
            $amount = $paymentData['amount']; //原来的付款金额

            if ($amount > 0) { //生成收款单
                $data = [
                    'payment_type' => '7',
                    'payment_method' => '1',
                    'amount' => $amount,
                    'refer' => 2, //来源于自收车辆
                    'create_time' => date('Y-m-d H:i:s', time()),
                    'branch_id' => $branchId, // 分公司编号
                ];
                $result = $collectionId = Collection::add($data);
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult(500, "添加收款单失败");
                }
                $auOrderObj = new AuOrder($order_id);
                $result = $auOrderObj->addCollectionAndOrderRelation($order_id, $collectionId, '7'); //7 应收车主
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult(500, "添加收款单拍单关系失败");
                }
                $selfReceiveCarData['collection_id'] = $collectionId; //收款单号
            }
        } elseif ($paymentStatus == 0 || $paymentStatus == 2) { //如果未付
            if ($paymentData) {
                $data['status'] = 3; //作废原来的未付款单
                $result = $paymentObj->update($data);
                if ($result === false) {
                    M()->rollback();
                    $this->helpJsonResult('500', '作废付款单失败');
                    return false;
                }
            }
        } elseif ($paymentStatus == 3) {
            M()->rollback();
            $this->helpJsonResult(500, "付款单信息有误");
        }
        return $selfReceiveCarData;
    }


    /**
     *自收车辆 - 其他渠道成交
     */
    public function self_receive_other_channel_deal()
    {
        $src_id = I('post.src_id/d', 0);
        $order_id = I('post.order_id/d', 0);
        $car_id = I('post.car_id/d', 0);
        if ($src_id < 1 || $order_id < 1 || $car_id < 1) {
            $this->helpJsonResult(400, "参数错误");
        }
        $src_info = $this->SelfReceiveCar->get_self_receive_car_detail($src_id);
        if (empty($src_info)) {
            $this->helpJsonResult(400, "未查询到自收车辆信息");
        }
        $trade_price = I('post.trade_price');
        if ($trade_price <= 0) {
            $this->helpJsonResult(400, "请输入正确的成交价");
        }

        $transfer_fee = I('post.transfer_fee');
        if ($transfer_fee < 0) {
            $this->helpJsonResult(400, "请输入正确的交付服务费");
        }

        $dealer_name = I('post.dealer');
        if (empty($dealer_name)) {
            $this->helpJsonResult(400, "请输入车商联系人");
        }
        $dealer_phone = I('post.dealer_phone');
        if (empty($dealer_phone)) {
            $this->helpJsonResult(400, "请输入车商联系人电话");
        }
        $take_car_man = I('post.take_car_man');
        if (empty($take_car_man)) {
            $this->helpJsonResult(400, "请输入提车人");
        }
        $trade_remark = I('post.trade_remark');
        $car = new Car($car_id);
        $carReport = new CarReportLogic($car_id);
        $branchId = $carReport->getBranchId();


        M()->startTrans();


        $car = new Car($car_id);
        $car_info = $car->detail();
        $rs3 = true;
        //车辆来源(1、4S店 2、个人)
        if ($car_info['car_source'] == 1) {
            $map = array();
            $map['car_id'] = ['eq', $car_id];
            $is_pay = M('pay_log')->where($map)->find();
            if (!$is_pay) {
                $params = [
                    'car_id' => $car_id,
                    'order_id' => $order_id,
                    'pay_type' => 1,
                    'status' => 0,
                    'createtime' => date('Y-m-d H:i:s')
                ];
                $rs3 = M('pay_log')->add($params);
            }

            $rs2 = $car->update(
                [
                    //'car_status' => 9, //其它渠道成交 - 交易成功
                    'deal_type' => 1,
                ]
            );
        } else {
            //三证合一(1、是 2、否)
            if ($car_info['three_in_one'] == 1) {
                $map = array();
                $map['car_id'] = ['eq', $car_id];
                $map['pay_type'] = ['eq', 1];
                $params = [
                    'car_id' => $car_id,
                    'order_id' => $order_id,
                    'status' => 0,
                    'createtime' => date('Y-m-d H:i:s')
                ];
                $is_first_pay = M('pay_log')->where($map)->find();
                if (!$is_first_pay) {
                    $params['pay_type'] = 1;
                    $rs3 = M('pay_log')->add($params);
                }
                $map1 = array();
                $map1['car_id'] = ['eq', $car_id];
                $map1['pay_type'] = ['eq', 2];
                $is_end_pay = M('pay_log')->where($map1)->find();
                if (!$is_end_pay) {
                    $params['pay_type'] = 2;
                    $rs3 = M('pay_log')->add($params);
                }
            } else {
                $map = array();
                $map['car_id'] = ['eq', $car_id];
                $map['pay_type'] = ['eq', 2];
                $params = [
                    'car_id' => $car_id,
                    'order_id' => $order_id,
                    'pay_type' => 2,
                    'status' => 0,
                    'createtime' => date('Y-m-d H:i:s')
                ];
                $is_pay = M('pay_log')->where($map)->find();
                if (!$is_pay) {
                    $rs3 = M('pay_log')->add($params);
                }
            }
            //交易类型改为其他渠道成交
            $carReportData = [
                'deal_type' => 1,
            ];
            $rs2 = $car->update($carReportData);
        }

        $auOrderObj = new AuOrder($order_id);
        $orderDetail = $auOrderObj->detail();
        //$orderNumber = $auOrderObj->createOrderNumber(1);//生成订单号
        $orderNumber = gen_order_no(); //生成拍单号

        unset($orderDetail['order_id']);
        $orderDetail['order_no'] = $orderNumber;
        $orderDetail['emp_id'] = $this->emp_id;
        $orderDetail['car_id'] = $car_id;
        $orderDetail['transfer_fee'] = $transfer_fee;
        $orderDetail['success_price'] = $trade_price;
        $orderDetail['is_lock'] = 0;
        $orderDetail['is_other_channel_deal'] = 1; //是否其他渠道提交
        $orderDetail['dealer_pay_status'] = 1; // 车商付款状态 改为未付款
        $orderDetail['last_time'] = date('Y-m-d H:i:s', time());//最后修改时间
        $orderDetail['create_time'] = date('Y-m-d H:i:s', time());//创建时间
        $orderDetail['status'] = 8; //已签约
        $orderDetail['return_check_status'] = 7;//回车复检状态，协商成功
        $orderDetail['check_car_status'] = 3; //验车状态，改为验车成功
        $orderDetail['is_owner_issue'] = 0; //车主不存在争议
        $orderDetail['is_dealer_issue'] = 0; //车商不存在争议
        $orderDetail['dealer_issue_status'] = 2; //协商成功
        $orderDetail['is_other_channel_deal'] = 1;// 其他渠道成交
        $orderDetail['refer'] = 2;

        $newOrderId = AuOrder::add($orderDetail);
        if ($newOrderId < 0) {
            M()->rollback();
            $this->helpJsonResult(500, '操作失败');
        }
        //新增order_fee
        $orderFeeData = [
            'success_price' => $trade_price,
            'transfer_fee' => $transfer_fee,
            'final_price' => $trade_price + $transfer_fee,
        ];
        $newOrder = new AuOrder($newOrderId);
        $resFee = $newOrder->addOrderFee($orderFeeData);
        if ($resFee < 0) {
            M()->rollback();
            Log::record("违约车辆，其他渠道成交，新增拍单费用失败，order_id: {$resFee} ");
            $this->helpJsonResult(500, '操作失败');
        }


        /*//更新采购单
        $poResult = PurchaseOrder::updateOrderIdBySid($car_info['sid'], $newOrderId, $orderNumber);
        if (!$poResult) {
            M()->rollback();
            Log::record("自收车辆其他渠道成交，更新采购单失败，car_id: {$car_info['car_id']}", "ERR", true);
            $this->helpJsonResult(500, "更新采购单失败");
        }*/

        //创建收款单
        $collectionData = [
            'payment_type' => '1',
            'payment_method' => '1',
            'amount' => $trade_price + $transfer_fee,
            'emp_id' => $this->emp_id,
            'emp_name' => $this->user_info['real_name'],
            'create_time' => date('Y-m-d H:i:s', time()),
            'branch_id' => $branchId, // 分公司编号
            'refer' => 2,
        ];
        $result3 = $this->createCollection($collectionData, $newOrderId);

        //更新自收车辆信息
        $rs1 = $this->SelfReceiveCar->update_self_receive_car($src_id,
            [
                'status' => 4,
                'trade_price' => $trade_price,
                'transfer_fee' => $transfer_fee,
                'dealer_name' => $dealer_name,
                'dealer_phone' => $dealer_phone,
                'take_car_man' => $take_car_man,
                'emp_id' => $this->emp_id,
                'emp_name' => $this->user_info['real_name'],
                'remark' => $trade_remark,
                'dealtime' => date("Y-m-d H:i:s"),
                'collection_id_car' => $result3, //车款 收款单号
                'd_order_id' => $newOrderId, //新生成的订单号
            ]
        );

        $unlockResult = $this->unLockAll($car); //解锁采购单和采购付款单失败

        if (!$unlockResult) {
            M()->rollback();
            $this->helpJsonResult(500, "解锁采购单，及采购付款单失败!");
        }
        // //更改车源状态
        // $CarSource = new CarSource($car_info['sid']);
        // $csData = [];
        // $csData['status'] = 500;
        // $res_cs = $CarSource->update($csData);

        if (!$rs1 || !$rs2 || !$rs3 || !$result3) {
            M()->rollback();
            $this->helpJsonResult(500, "操作失败");
        }


        M()->commit();
        $this->log_record($car_id, $newOrderId, '自收车辆，其他渠道成交');
        $this->helpJsonResult(200, 'success');
    }

    /**
     * 创建收款单
     *
     * @param array $collectionData 收款单信息
     * @param int $orderId 拍单编号
     * @return bool 返回true/false
     */
    public function createCollection($collectionData, $orderId)
    {
        $collectionId = Collection::add($collectionData);
        if ($collectionId === false) {
            return false;
        }

        $orderObj = new AuOrder($orderId);
        $result = $orderObj->addCollectionAndOrderRelation($orderId, $collectionId, '1');//收款类型等于1，表示车款应收
        if ($result === false) {
            return false;
        }
        return $collectionId;
    }

    //记录日志信息
    private function log_record($car_id, $order_id, $action)
    {
        //记录员工操作日志
        $log = [
            'emp_id' => $this->emp_id,
            'order_id' => $order_id,
            'car_id' => $car_id,
            'owner_id' => 0,
            'action' => $action
        ];
        \AuctionCore\System\SystemLog::add($log);

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => $action,
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($car_id, $car_action_data);

        /*记录拍品跟踪日志*/
        $order_action_data = array(
            'action_name' => $action,
            'emp_id' => $this->emp_id
        );
        AuOrder::add_order_trace_log($order_id, $order_action_data);
    }
}